import { reactive, ref } from "vue"
import {getRoleMenuList} from '@/api/menu'
import {assignSaveApi} from '@/api/role'
import useInstance from '@/hooks/useInstance';
export const useRoleAssignMenu = (dialog, onClose, onShow, emit) => {
  const {global}  = useInstance()
   //权限树的ref属性
 const assignTree = ref()
   //定义分配权限保存的参数
   const saveParm = reactive({
    roleId: '',
    menusIds: []
})
  const show =(roleId,roleName)=>{
     //数据
     assignTreeData.list = []
     assignTreeData.assignTreeChecked = []
     //设置角色id
     saveParm.roleId = roleId;
    
     //查询权限树的数据
    getAssignTree(roleId);
    dialog.title=`为【${roleName}】分配权限`
    dialog.height = 220
    dialog.width = 350
    onShow()
  }
  const confirm =async ()=>{
     //获取选中的数据
     let checkedIds = assignTree.value?.getCheckedKeys(false) || []
     //获取半节点ids
     let hlfIds = assignTree.value?.getHalfCheckedKeys() || []
     saveParm.menusIds = checkedIds?.concat(hlfIds)
     //提交保存
     let res = await assignSaveApi(saveParm)
     if (res && res.code == 200) {
         //信息提示
         global.$message({message:res.msg,type:'success'})
         //关闭弹框
         onClose()
     }
  }

 //树的属性配置
 const defaultProps = reactive({
     children: 'children',
     label: 'label',
 })
 //权限树数据
 const assignTreeData = reactive({
     list: [],
     assignTreeChecked: [] //原来分配的权限id的集合
 })
  //获取权限树数据
  const getAssignTree = async (parm) => {
    let res = await getRoleMenuList(parm)
    if (res && res.code == 200) {
        //设置权限树数据
        assignTreeData.list = res.data.allMenus

       let  checkList = res.data.checkList
        let checkedList = []
       checkList.forEach((item) => {
        if(item.children && item.children.length!= 0){
            item.children.forEach((num)=>{
                checkedList.push(num.id)
            }) 
        }
          checkedList.push(item.id)          
       })
        console.log("🚀 ~ file: useRoleAssignMenu.js:53 ~ checkList.forEach ~ checkList:", checkedList)
        //设置角色原来的权限Id
        assignTreeData.assignTreeChecked = checkedList
        //数据回显，判断角色原来是否已经分配过权限，如果有，回显
        if (assignTreeData.assignTreeChecked.length > 0) {
            let newArr = [];
            assignTreeData.assignTreeChecked.forEach((item => {
                checked(item, assignTreeData.list, newArr)
            }))
            assignTreeData.assignTreeChecked = newArr;
        }
    }
}
const checked = (id, data, newArr) => {
    data.forEach((item) => {
        if (item.id == id) {
            if (item.children && item.children.length == 0) {
                newArr.push(item.id)
            }
        } else {
            if (item.children && item.children.length != 0) {
                //递归调用
                checked(id, item.children, newArr)
            }
        }
    })
}
  return{show,confirm,assignTree,assignTreeData,defaultProps}
}